<?php

namespace Common\Bundle\ApplicationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;

use Common\Bundle\LibraryBundle\Entity\Statistique;

class ApplicationController extends Controller
{
    /**
     * @Route("/")
     * @Template()
     */
    public function indexAction(Request $request)
    {
        /** @var $session \Symfony\Component\HttpFoundation\Session\Session */
        $session = $request->getSession();

        // get the error if any (works with forward and redirect -- see below)
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } elseif (null !== $session && $session->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = '';
        }

        if ($error) {
            // TODO: this is a potential security risk (see http://trac.symfony-project.org/ticket/9523)
            $error = $error->getMessage();
        }
        // last username entered by the user
        $lastUsername = (null === $session) ? '' : $session->get(SecurityContext::LAST_USERNAME);

        $csrfToken = $this->container->has('form.csrf_provider')
            ? $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate')
            : null;

        return array('last_username' => $lastUsername,
            'error'         => $error,
            'csrf_token' => $csrfToken,);
    }

    /**
     * @Route("/connexion")
     */
    public function connexionAction(Request $request)
    {
        
        $request = $this->getRequest();
        $login = "";
        $mdp = "";

        $donnees = "{}";

        if($request->isXmlHttpRequest()){
            $login = $request->get("login");
            $mdp = $request->get("mdp");

            if($login != "" && $mdp!=""){
               $donnees = $this->getUserRepository()->findOneForFront($login,$mdp);
               if(count($donnees) > 0){
                    $donnees = $donnees[0];
               }
               else{
                    $donnees = "{}";
               }
            }

        }
         return new Response(json_encode($donnees));
    }

     /**
     * @Route("/contact")
     */
    public function contactAction(Request $request)
    {
        
        $request = $this->getRequest();
        $tabContacts = "";
        $tabDonnees = array();

        if($request->isXmlHttpRequest()){
            $tabContacts = json_decode($request->get("tabContacts"));
            
            if(count($tabContacts)>0){
                  
                $mailFrom = "eye.qcm@gmail.com";
                $mailTo = "eye.qcm@gmail.com";
               
                foreach($tabContacts as $demande){
                     
                    $user = $this->getUserRepository()->find($demande->utilisateur_id);

                    $mailObjet = "eYe - ".$demande->type_demande;
                    
                    $mailContent = $mailObjet."\n\n";;
                    $mailContent .= "Adresse Mail : \n".$user->getEmail()."\n\n";
                    
                    if($demande->qcm_id != -1){
                        $qcm = $this->getQcmRepository()->find($demande->qcm_id);
                        $mailContent .= "QCM concerné :  \n". $qcm->getNom()." (id : ".$qcm->getId()." )\n\n";
                    }
                    
                    $mailContent .= "Message : \n".$demande->message;
                                  
                    $message = \Swift_Message::newInstance()
                        ->setSubject($mailObjet)
                        ->setFrom($mailFrom)
                        ->setTo($mailTo)
                        ->setBody($mailContent);

                    $verif = $this->get('mailer')->send($message)."/";
                  
                    if(!$verif){
                        $tabDonnees[] = $demande;
                    }
                }

            }

        }
        
        return new Response(json_encode($tabDonnees));
    }

    /**
    * @Route("/statistiques")
    */
    public function statistiquesAction(Request $request)
    {
        $tabDonnees = array();
        
        $request = $this->getRequest();
        $tabStatistiques = "";
        $idUser = "";

        if($request->isXmlHttpRequest()){
            $tabStatistiques = json_decode($request->get("statistiques"));
            $idUser =  $request->get("id_user");

            if(is_numeric($idUser)){
               $user = $this->getUserRepository()->find($idUser);

                if(count($tabStatistiques) > 0){                   
                    foreach ($tabStatistiques as $stat) {                                      
                        $statistique = new Statistique();
                        $statistique->setNote($stat->note);
                        $statistique->setDate($stat->date);
                        $statistique->setUser($user);

                        $qcm = $this->getQcmRepository()->find($stat->qcm_id);
                        $statistique->setQcm($qcm);
                       
                        $this->getDoctrine()->getManager()->persist($statistique);               
                    }
                    $this->getDoctrine()->getManager()->flush();
                } 

                $tabDonnees = $this->getStatistiqueRepository()->findAllForFront($idUser);
            }
            
        }

        return new Response(json_encode($tabDonnees));
    }
	
	/**
    * @Route("/donnees")
    */
    public function donneesAction()
    {
               
        $tabDonnees = array();
       
        $tabDonnees["tabThemes"] = $this->getThemeRepository()->findAllForFront();
        $tabDonnees["tabQcms"] = $this->getQcmRepository()->findAllForFront();
        $tabDonnees["tabQuestions"] = $this->getQuestionRepository()->findAllForFront();
        $tabDonnees["tabReponses"] = $this->getReponseRepository()->findAllForFront();
        $tabDonnees["tabNiveaux"] = $this->getNiveauRepository()->findAllForFront();
        $tabDonnees["tabDifficultes"] = $this->getDifficulteRepository()->findAllForFront();
        $tabDonnees["tabEvaluations"] = $this->getEvaluationRepository()->findAllForFront();

        return new Response(json_encode($tabDonnees));
    }

    /**
     * @Route("/quisommesnous")
     * @Template()
     */
    public function quisommesnousAction()
    {
        return array();
    }
   

    /**
    * @return \Common\Bundle\LibraryBundle\Entity\Repository\ThemeRepository
    */
    protected function getThemeRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Theme');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\QcmRepository
     */
    protected function getQcmRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Qcm');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\QuestionRepository
     */
    protected function getQuestionRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Question');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\ReponseRepository
     */
    protected function getReponseRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Reponse');
    }

     /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\NiveauRepository
     */
    protected function getNiveauRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Niveau');
    }

     /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\DifficulteRepository
     */
    protected function getDifficulteRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Difficulte');
    }

    /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\EvaluationRepository
     */
    protected function getEvaluationRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Evaluation');
    }

    /**
     * @return \Common\Bundle\UserBundle\Entity\Repository\UserRepository
     */
    protected function getUserRepository() {
        return $this->getDoctrine()->getRepository('CommonUserBundle:User');
    }

     /**
     * @return \Common\Bundle\LibraryBundle\Entity\Repository\StatistiqueRepository
     */
    protected function getStatistiqueRepository() {
        return $this->getDoctrine()->getRepository('CommonLibraryBundle:Statistique');
    }



}
